<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
  <link href="./styles.css" rel="stylesheet" />
  <!-- 引入layui -->
  <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
  <script src="https://www.layuicdn.com/layui/layui.js"></script>
  <title>demo</title>
  </script>
</head>

<body>
  <div id="app">
    <h1>主页，服务端</h1>
    <p>WebSocket地址：ws://<span id="localIp"></span>:9000</p>
    <!-- <button id="setFull" type="button">F11</button> -->
    <!-- 复制整个websocket地址   -->
    <button id="copyWebsocket" type="button">复制websocket地址</button>
    
  </div>
  <!-- You can also require other files to run in this process -->
  <script src="./renderer.js"></script>
  <script>
    function getLocalIp() {
      // 使用RTCPeerConnection来获取本地IP地址
      const pc = new RTCPeerConnection({
        iceServers: []
      });
      
      pc.createDataChannel('');
      pc.createOffer()
        .then(offer => pc.setLocalDescription(offer))
        .catch(err => console.error(err));

      pc.onicecandidate = (event) => {
        if (!event.candidate) return;
        
        // 从candidate中提取IP地址
        const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
        const match = ipRegex.exec(event.candidate.candidate);
        
        if (match) {
          const localIp = match[1];
          // 检查是否为局域网IP
          if (localIp.startsWith('192.168.') || 
              localIp.startsWith('10.') || 
              localIp.startsWith('172.')) {
            document.getElementById('localIp').textContent = localIp;
            pc.close();
          }
        }
      };
    }
    getLocalIp();
    document.getElementById('copyWebsocket').addEventListener('click', () => {
      const websocketUrl = `ws://${document.getElementById('localIp').textContent}:9000`;
      navigator.clipboard.writeText(websocketUrl);
      alert('已复制websocket地址');
    }); 
  </script>
</body>

</html>